//
//  ViewController.swift
//  SwiftTest
//
//  Created by 陈旺 on 2022/1/19.
//

import UIKit
import AVFoundation
import AVKit

class ViewController: UIViewController {


    private let imgPaths: [String] = [
        "path0", "path1", "path2", "path3", "path4", "path5", "path6"
    ]

    var button: UIButton!

    private var imgs: [String] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .orange
        self.navigationItem.title = "home"

        let button = UIButton(type: .system)
        button.setTitle("点击跳转", for: .normal)
        button.setTitleColor(.white, for: .normal)
        button.addTarget(self, action: #selector(buttonClick), for: .touchUpInside)
        button.frame = CGRect(x: 100, y: 200, width: 100, height: 50)
        view.addSubview(button)
        self.button = button




//        Task {
//            debugPrint(Date())
//
//            let img = await downloadImage(path: imgPaths[0])
//
//            async let img = downloadImage(path: imgPaths[0])
//            async let img1 = downloadImage(path: imgPaths[1])
//            await debugPrint(img, img1, Date())
//
//            let imgs = await downloadImages(paths: self.imgPaths)
//            debugPrint(Date(), imgs)
//        }
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }

    @objc private func buttonClick() {

        let value1 = UserDefaults.standard.string(forKey: "key1")
        if value1 == "2" {
            self.view.backgroundColor = .blue
        }

        let value = UserDefaults.standard.string(forKey: "key2")
        if value == "3" {
            self.button.setTitleColor(.black, for: .normal)
        }else if value == "4" {
            self.button.setTitleColor(.red, for: .normal)
        }
//        let controller = CWShortVideoController()
//        self.navigationController?.pushViewController(controller, animated: true)
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        let controller = CWShortVideoController()
        self.navigationController?.pushViewController(controller, animated: true)
    }

    /// 模拟下载图片
    private func downloadImage(path: String) async -> String {
        try? await Task.sleep(nanoseconds: 3 * 1_000_000_000)
        debugPrint(Thread.current)
        return "图片+\(path)"
    }

    private func downloadImages(paths: [String]) async -> [String] {
        var imgs: [String] = []
        try? await withThrowingTaskGroup(of: String.self, body: { group in
            paths.forEach { item in
                group.addTask(priority: .medium) { [self] in
                    return await downloadImage(path: item)
                }
            }
            for try await img in group {
                imgs.append(img)
            }
        })
        return imgs
    }

    @MainActor private func main() {

    }
}

